/**
 * 每日早报页面
 * 使用 axios 调用早报 API
 */

import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Image,
  ActivityIndicator,
  RefreshControl,
  Alert,
  useColorScheme,
  TouchableOpacity,
  Linking,
  Dimensions,
} from 'react-native';
import axios from 'axios';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import API_CONFIG from './config';

interface NewsPageProps {
  onBackToHome?: () => void;
  onNavigateToImage?: (imageUrl: string) => void;
}

interface NewsData {
  date: string;
  news: string[];
  weiyu: string;
  image: string;
  head_image: string;
}

const NewsPage: React.FC<NewsPageProps> = ({onBackToHome, onNavigateToImage}) => {
  const [newsData, setNewsData] = useState<NewsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const isDarkMode = useColorScheme() === 'dark';

  const fetchNews = async () => {
    try {
      const response = await axios.post(API_CONFIG.ZAOBAO_API.url, {
        token: API_CONFIG.ZAOBAO_API.token,
        format: API_CONFIG.ZAOBAO_API.format,
      });

      if (response.data && response.data.code === 200) {
        setNewsData(response.data.data);
      } else {
        Alert.alert('错误', '获取早报数据失败');
      }
    } catch (error) {
      console.error('API Error:', error);
      Alert.alert('网络错误', '请检查网络连接后重试');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchNews();
  }, []);

  const onRefresh = () => {
    setRefreshing(true);
    fetchNews();
  };

  const openImage = (imageUrl: string) => {
    console.log('Opening image with URL:', imageUrl);
    
    if (onNavigateToImage) {
      // 使用路由跳转
      onNavigateToImage(imageUrl);
    } else {
      // 使用系统浏览器打开
      Linking.openURL(imageUrl).catch(err => {
        console.error('Failed to open image:', err);
        Alert.alert('错误', '无法打开图片，请检查网络连接');
      });
    }
  };

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const contentStyle = {
    backgroundColor: isDarkMode ? Colors.black : Colors.white,
  };

  if (loading) {
    return (
      <View style={[styles.container, backgroundStyle]}>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#007AFF" />
          <Text style={[styles.loadingText, {color: isDarkMode ? Colors.white : Colors.black}]}>
            正在加载早报...
          </Text>
        </View>
      </View>
    );
  }

  return (
    <View style={[styles.container, backgroundStyle]}>
      <ScrollView
        style={contentStyle}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }>
        
        {/* 头部标题 */}
        <View style={styles.header}>
          <View style={styles.headerTop}>
            {onBackToHome && (
              <TouchableOpacity style={styles.backButton} onPress={onBackToHome}>
                <Text style={styles.backButtonText}>← 返回</Text>
              </TouchableOpacity>
            )}
            <Text style={[styles.headerTitle, {color: isDarkMode ? Colors.white : Colors.black}]}>
              📰 每日早报
            </Text>
          </View>
          {newsData?.date && (
            <Text style={[styles.dateText, {color: isDarkMode ? Colors.light : Colors.dark}]}>
              {newsData.date}
            </Text>
          )}
        </View>

        {/* 头图 */}
        {newsData?.head_image && (
          <View style={styles.newsImageContainer}>
            <Image
              source={{uri: newsData.head_image}}
              style={styles.headImage}
              resizeMode="cover"
            />
          </View>
        )}

        {/* 微语 */}
        {newsData?.weiyu && (
          <View style={styles.weiyuContainer}>
            <Text style={[styles.weiyuTitle, {color: isDarkMode ? Colors.white : Colors.black}]}>
              💭 微语
            </Text>
            <Text style={[styles.weiyuText, {color: isDarkMode ? Colors.light : Colors.dark}]}>
              {newsData.weiyu}
            </Text>
          </View>
        )}

        {/* 新闻内容 */}
        {newsData?.news && newsData.news.length > 0 && (
          <View style={styles.newsContainer}>
            <Text style={[styles.newsTitle, {color: isDarkMode ? Colors.white : Colors.black}]}>
              📋 今日新闻
            </Text>
            {newsData.news.map((newsItem, index) => (
              <View key={index} style={styles.newsItem}>
                <Text style={[styles.newsItemText, {color: isDarkMode ? Colors.light : Colors.dark}]}>
                  {newsItem}
                </Text>
              </View>
            ))}
          </View>
        )}

        {/* 早报图片 */}
        {newsData?.image && (
          <View style={styles.newsImageContainer}>
            <Text style={[styles.imageTitle, {color: isDarkMode ? Colors.white : Colors.black}]}>
              🖼️ 早报图片
            </Text>
            <TouchableOpacity onPress={() => openImage(newsData.image)}>
              <Image
                source={{uri: newsData.image}}
                style={styles.newsImage}
                resizeMode="cover"
              />
              <View style={styles.imageOverlay}>
                <Text style={styles.imageOverlayText}>点击查看大图</Text>
              </View>
            </TouchableOpacity>
          </View>
        )}

        {/* 底部刷新按钮 */}
        <View style={styles.footer}>
          <TouchableOpacity style={styles.refreshButton} onPress={onRefresh}>
            <Text style={styles.refreshButtonText}>🔄 刷新早报</Text>
          </TouchableOpacity>
          {newsData?.image && (
            <TouchableOpacity 
              style={[styles.refreshButton, {backgroundColor: '#FF6B6B', marginTop: 10}]} 
              onPress={() => openImage(newsData.image)}>
              <Text style={styles.refreshButtonText}>🖼️ 查看大图</Text>
            </TouchableOpacity>
          )}
          <TouchableOpacity 
            style={[styles.refreshButton, {backgroundColor: '#34C759', marginTop: 10}]} 
            onPress={() => openImage('https://via.placeholder.com/400x300/007AFF/FFFFFF?text=Test+Image')}>
            <Text style={styles.refreshButtonText}>🧪 测试图片查看</Text>
          </TouchableOpacity>
        </View>

      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
  },
  header: {
    padding: 20,
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
  },
  headerTop: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
    justifyContent: 'center',
  },
  backButton: {
    position: 'absolute',
    left: 0,
    padding: 8,
  },
  backButtonText: {
    fontSize: 16,
    color: '#007AFF',
    fontWeight: '600',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  dateText: {
    fontSize: 16,
    fontWeight: '500',
  },
  weiyuContainer: {
    padding: 20,
    backgroundColor: '#F8F9FA',
    margin: 16,
    borderRadius: 12,
  },
  weiyuTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 12,
  },
  weiyuText: {
    fontSize: 16,
    lineHeight: 24,
  },
  newsContainer: {
    padding: 20,
  },
  newsTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 12,
  },
  newsText: {
    fontSize: 16,
    lineHeight: 24,
  },
  newsItem: {
    marginBottom: 12,
    paddingLeft: 8,
    borderLeftWidth: 3,
    borderLeftColor: '#007AFF',
  },
  newsItemText: {
    fontSize: 16,
    lineHeight: 24,
  },
  newsImageContainer: {
    padding: 20,
  },
  imageTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 12,
  },
  headImage: {
    width: '100%',
    height: 200,
    borderRadius: 12,
  },
  newsImage: {
    width: '100%',
    height: 300,
    borderRadius: 12,
  },
  footer: {
    padding: 20,
    alignItems: 'center',
  },
  refreshButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  refreshButtonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '600',
  },
  imageOverlay: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    paddingVertical: 8,
    paddingHorizontal: 12,
    alignItems: 'center',
  },
  imageOverlayText: {
    color: 'white',
    fontSize: 14,
    fontWeight: '600',
  },
});

export default NewsPage;
